<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="书籍名称" prop="bookName">-->
<!--        <el-input-->
<!--          v-model="queryParams.bookName"-->
<!--          placeholder="请输入书籍名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:shopcart:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-discount"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleAddOrder"-->
<!--          v-hasPermi="['system:order:add']"-->
<!--        >结算</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:shopcart:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:shopcart:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:shopcart:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopcartList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="购物车商品ID" align="center" prop="scId" />
      <el-table-column label="用户姓名" align="center" prop="username" />
      <el-table-column label="书籍名称" align="center" prop="bookName" />
      <el-table-column label="售价" align="center" prop="rePrice" />
<!-- 显示单价-->
      <el-table-column label="数量" align="center" prop="num" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:shopcart:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:shopcart:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-sell"
            @click="handleAddOrder(scope.row)"
            v-hasPermi="['system:order:add']"
          >立即购买</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改购物车信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="书籍名称" prop="bookName">
          <el-input v-model="form.bookName" placeholder="请输入书籍名称" :disabled="true" />
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入数量" />
        </el-form-item>
<!--        <el-form-item label="删除字段" prop="isDel">-->
<!--          <el-input v-model="form.isDel" placeholder="默认为0(未删除)" />-->
<!--      </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
  </div>
  </el-dialog>

    <!--结算对话框（需要显示单价-->
    <el-dialog :title="title" :rules="rules" :visible.sync="openOrder" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="书名" prop="bookName">
          <el-input v-model="form.bookName" placeholder="请输入书名" :disabled="true"/>
        </el-form-item>
        <el-form-item label="售价/现价" prop="rePrice">
          <el-input v-model="form.rePrice" placeholder="$xx" :disabled="true"/>
        </el-form-item>
        <el-form-item label="购买数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入购买数量" />
        </el-form-item>

        <!-- 这里填地址咯 -->
        <el-form-item label="手机号" prop="tele">
          <el-input v-model="form.tele" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-select v-model="form.address"  placeholder="请选择地址" clearable>
            <el-option
              v-for="item in addressOptions"
              :key="item.id"
              :label="item.address"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="总计" prop="payPrice">
          <span>¥{{TotalPrice}}元</span>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormOrder">购买</el-button>
        <el-button @click="cancelO">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listShopcart, getShopcart, delShopcart, addShopcart, updateShopcart } from "@/api/system/shopcart";
import {getBookinfo, updateBookinfo} from "@/api/system/bookinfo";
import {addOrder} from "@/api/system/order";
import {listAddress} from "@/api/system/address";

export default {
  name: "Shopcart",
  data() {
    return {
      tableData:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数

      //地址信息
      addressOptions:[],

      total: 0,
      // 购物车信息表格数据
      shopcartList: [],
      //确认信息表格数据
      confirmList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openOrder:false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        bookId: null,
        stock:null,
        num: null,
        isDel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询购物车信息列表 */
    getList() {
      this.loading = true;
      listShopcart(this.queryParams).then(response => {
        this.shopcartList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelO() {
      this.openOrder = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scId: null,
        userId: null,
        bookId: null,
        num: null,
        isDel: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加购物车信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.reset();
      const scId = row.scId || this.ids
      getShopcart(scId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改购物车信息";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.scId != null) {
            updateShopcart(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShopcart(this.form).then(response => {
              console.log(this.form)
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scIds = row.scId || this.ids;
      this.$modal.confirm('是否确认删除购物车信息编号为"' + scIds + '"的数据项？').then(function() {
        return delShopcart(scIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /**立即购买操作*/
    handleAddOrder(row){
      this.reset();
      const scIds = row.scId || this.ids
      listAddress().then(response =>{
        this.addressOptions =response.rows;
      })
      getShopcart(scIds).then(response => {
        this.form = response.data;
        this.openOrder = true;
        this.title = "请确认订单信息并填写正确的收货地址";
      });
    },
    /**加入购物车弹窗提交按钮——未修改完毕*/
    submitFormOrder() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          // if(this.form.num > 0){
          //   if(this.form.num > this.form.stock){
          //     this.$modal.msgError("货存不足，请重新选择");
          //   }else{
              if (this.form.scId != null) {
                var _this = this;
                console.log(this.form);
                console.log(this.form.stock);
                addOrder(this.form).then(response => {
                  this.$modal.msgSuccess("购买成功，快去看看吧");
                  _this.form.stock = _this.form.stock - _this.form.num;
                  updateBookinfo(_this.form)
                  const scIds = _this.form.scId;
                  delShopcart(scIds);
                  this.openOrder = false;
                });
              }}
          // }else{
          //   this.$modal.msgError("您输入的数量不正确，请重新输入");
          // }}
      });
    },
    /**结算按钮操作,未完成,需学习*/
    // handleAddOrder(row){
    //   //this.reset();
      // const bookName = row.bookName  || this.ids
      // const bookNum = row.num || this.ids
      // const scIds = row.scId || this.ids;
      // this.openOrder = true;
      // this.title = "结算";
      // this.loading = true;
      // for (var i = 0; i < scIds.length; i++) {
      //   getShopcart(scIds).then(response => {
      //     this.tableData[i] = response.data;
      //     this.loading = false;
      //   });
      // }
      // this.confirmList = this.ids;
      // this.$modal.confirm('是否确认购买"' +  + '"？').then(function() {
      //   return delShopcart();
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("购买成功！快去看看吧~");
      // }).catch(() => {});
      // getBookinfo(bookId).then(response => {
      //
      //   this.openOrder = true;
      //   this.title = "结算";
      // });
    // },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/shopcart/export', {
        ...this.queryParams
      }, `shopcart_${new Date().getTime()}.xlsx`)
    }
  },
  computed:{
    TotalPrice(){
      let aData = new Date();
      if(this.form.num) {
        this.form.payPrice = this.form.num * this.form.rePrice;
        this.form.orPrice = this.form.rePrice;
        this.form.orderTime = aData;
        this.form.pNum = this.form.num;
        return this.form.num * this.form.rePrice;
      }else{
        return 0
      }
    }
  }
};


</script>
